// 本地的用户信息验证
const auth = {
  randomString: function (len, rad) {
    let CHARS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('')
    let chars = CHARS
    let uuid = []
    let i = null
    let radix = (rad && rad > chars.length ? chars.length : rad) || chars.length
    if (len) {
      for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix]
    } else {
      let r
      // 定义规则生成用户的token
      uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-'
      uuid[14] = '4'
      for (i = 0; i < 36; i++) {
        if (!uuid[i]) {
          r = 0 | Math.random() * 16
          uuid[i] = chars[(i === 19) ? (r & 0x3) | 0x8 : r]
        }
      }
    }
    return uuid.join('')
  },
  getUid: function () {
    let uid = window.localStorage.getItem('imp-uuid')
    if (!uid) {
      uid = this.randomString()
      window.localStorage.setItem('imp-uuid', uid)
    }
    return uid
  },
  getSid: function () {
    let sid = window.localStorage.getItem('imp-sid')
    if (sid) {
      return sid
    }
    return ''
  },
  login (token, callback) {
    window.localStorage.setItem('imp-sid', token)
    if (callback) callback()
  },
  getToken () {
    return window.localStorage.getItem('imp-sid')
  },
  logout (cb) {
    window.localStorage.removeItem('imp-sid')
    if (cb) cb()
  },
  loggedIn () {
    return !!window.localStorage.getItem('imp-sid')
  }
}

export default auth
